package cn.harry.cabinet.repository

import android.app.Application
import cn.harry.cabinet.database.AppDatabase
import cn.harry.cabinet.model.entity.OperationLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * 操作日志数据仓库
 */
class OperationLogRepository(application: Application) : BaseRepository() {
    
    private val operationLogDao = AppDatabase.getDatabase(application).operationLogDao()
    
    /**
     * 插入日志
     */
    suspend fun insert(log: OperationLog) = withContext(Dispatchers.IO) {
        operationLogDao.insert(log)
    }
    
    /**
     * 批量插入日志
     */
    suspend fun insertAll(logs: List<OperationLog>) = withContext(Dispatchers.IO) {
        operationLogDao.insertAll(logs)
    }
    
    /**
     * 获取所有日志
     */
    suspend fun getAll(): List<OperationLog> = withContext(Dispatchers.IO) {
        operationLogDao.getAll()
    }
    
    /**
     * 根据ID获取日志
     */
    suspend fun getById(id: Long): OperationLog? = withContext(Dispatchers.IO) {
        operationLogDao.getById(id)
    }
    
    /**
     * 根据操作类型获取日志
     */
    suspend fun getByType(type: String): List<OperationLog> = withContext(Dispatchers.IO) {
        operationLogDao.getByType(type)
    }

    /**
     * 分页获取日志
     */
    suspend fun getPagedLogs(limit: Int, offset: Int): List<OperationLog> = 
        withContext(Dispatchers.IO) {
            operationLogDao.getPagedLogs(limit, offset)
        }
    
    /**
     * 获取日志总数
     */
    suspend fun getCount(): Int = withContext(Dispatchers.IO) {
        operationLogDao.getCount()
    }
    
    /**
     * 删除指定时间之前的日志
     */
    suspend fun deleteBeforeTime(timestamp: Long): Int = withContext(Dispatchers.IO) {
        operationLogDao.deleteBeforeTime(timestamp)
    }
    
    /**
     * 删除所有日志
     */
    suspend fun deleteAll() = withContext(Dispatchers.IO) {
        operationLogDao.deleteAll()
    }
    
    /**
     * 复合查询：按多个条件筛选日志
     */
    suspend fun searchLogs(
        type: String?,
        result: String?,
        operatorId: Long?,
        startTime: Long?,
        endTime: Long?,
        limit: Int,
        offset: Int
    ): List<OperationLog> = withContext(Dispatchers.IO) {
        operationLogDao.searchLogs(type, result, operatorId, startTime, endTime, limit, offset)
    }
}
